package cn.org.donald.framework.util;

import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author : Donald
 * @since : 2020/11/16 16:58
 */
public class StringUtil extends StringUtils {

    private static final String verifyPhone = "^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$";

    /**
     * Hide mainland phone number
     * @param phone
     * @return
     */
    public static String hideMainlandPhone(String phone){
        try {
            if (phone.matches(verifyPhone)){
                return phone.substring(0,3) + "****" + phone.substring(7,11);
            }else {
                throw new IllegalAccessException("This phone can not format, it is not a Chinese Mainland phone number! argument: "+phone);
            }
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * get string from input stream
     * @param inputStream
     * @param charset
     * @return
     * @throws IOException
     */
    public static String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
            StringBuilder sb = new StringBuilder();
            final char[] chars = new char[1024];
            int read = 0;
            while ((read = inputStreamReader.read(chars)) > 0){
                sb.append(chars,0,read);
            }
            return sb.toString();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (inputStream != null){
                inputStream.close();
            }
        }
        return null;
    }

    public static boolean isNotEmpty(Object o){
        return !StringUtil.isEmpty(o);
    }
}
